package com.hlt.controller.user;


import com.hlt.context.BaseContext;
import com.hlt.dto.PostCreateDTO;
import com.hlt.dto.UserPostsPageQueryDTO;
import com.hlt.entity.Posts;
import com.hlt.entity.SensitiveWordRecord;
import com.hlt.result.PageResult;
import com.hlt.result.Result;
import com.hlt.service.ICategoriesService;
import com.hlt.service.IPostsService;
import com.hlt.service.ISensitiveWordRecordService;
import com.hlt.utils.SensitiveWordUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lzf
 * @since 2024-11-25
 */
@RestController
@Controller("userPostsController")
@RequestMapping("/users/posts")
@Api(tags = "用户文章接口")
public class PostsController {
    @Autowired
    private IPostsService postsService;

    @Autowired
    private ICategoriesService categoriesService;

    @Autowired
    private SensitiveWordUtil sensitiveWordUtil;

    @Autowired
    private ISensitiveWordRecordService sensitiveWordRecordService;

    @PostMapping
    @ApiOperation("发布文章")
    public Result save(@Valid @RequestBody PostCreateDTO postDTO) {
        // 检测文章标题和内容中的敏感词
        String title = postDTO.getTitle();
        String content = postDTO.getContent();
        Long userId = BaseContext.getCurrentId();

        SensitiveWordRecord record = null;

        // 检测标题
        if (sensitiveWordUtil.contains(title)) {
            List<String> titleSensitiveWords = sensitiveWordUtil.findAll(title);
            // 保存敏感词记录
            record = new SensitiveWordRecord();
            record.setUserId(userId);
            record.setContent(content);
            record.setSensitiveWords(String.join(",", titleSensitiveWords));
            record.setCreatedAt(LocalDateTime.now());
            sensitiveWordRecordService.save(record);  // 新增保存操作
            Result.error("文章标题包含敏感词：" + String.join("、", titleSensitiveWords));
        }
        // 检测内容敏感词
        if (sensitiveWordUtil.contains(content)) {
            List<String> contentSensitiveWords = sensitiveWordUtil.findAll(content);
            // 保存敏感词记录
            record = new SensitiveWordRecord();
            record.setUserId(userId);
            record.setContent(content);
            record.setSensitiveWords(String.join(",", contentSensitiveWords));
            record.setCreatedAt(LocalDateTime.now());
            sensitiveWordRecordService.save(record);  // 新增保存操作
            Result.error("文章内容包含敏感词：" + String.join("、", contentSensitiveWords));
        }

        // 将 DTO 转换为实体
        Posts post = new Posts();
        post.setTitle(postDTO.getTitle());
        post.setContent(postDTO.getContent());
        post.setCategoryId(postDTO.getCategoryId());
        post.setStatus(1); // 默认发布状态
        post.setUserId(Math.toIntExact(userId));// 设置用户信息

        // 保存并处理分类计数
        postsService.save(post);
        if(postDTO.getCategoryId() != null) {
            categoriesService.addCount(Long.valueOf(postDTO.getCategoryId()));
        }

        record.setContentId(Long.valueOf(post.getPostId()));
        sensitiveWordRecordService.updateById(record);

        return Result.success(post.getPostId());
    }

    // 新增保存草稿接口（前端加一个保存草稿的按钮就行了）
    @PostMapping("/draft")
    @ApiOperation("保存文章草稿")
    public Result saveDraft(@Valid @RequestBody PostCreateDTO postDTO) {
        // 转换DTO为实体
        Posts post = new Posts();
        post.setTitle(postDTO.getTitle());
        post.setContent(postDTO.getContent());
        post.setCategoryId(postDTO.getCategoryId());
        post.setStatus(0); // 草稿状态设为0

        // 设置用户信息（复用发布逻辑中的用户ID获取）
        Long userId = BaseContext.getCurrentId();
        post.setUserId(Math.toIntExact(userId));

        // 保存草稿（不触发分类计数更新）
        postsService.save(post);

        return Result.success(post.getPostId());
    }

    @PutMapping("/{postId}")
    @ApiOperation("修改个人文章")
    public Result updatePost(@PathVariable Integer postId, @RequestBody PostCreateDTO postDTO) {
        // 验证文章归属
        Posts existingPost = postsService.getById(postId);
        if (existingPost == null || !existingPost.getUserId().equals(Math.toIntExact(BaseContext.getCurrentId()))) {
            return Result.error("无权修改该文章");
        }

        postDTO.setPostId(postId);
        postsService.updateById(postDTO);
        return Result.success();
    }

    @DeleteMapping("/{postId}")
    @ApiOperation("删除个人文章")
    public Result deletePost(@PathVariable Integer postId) {
        Posts posts = postsService.getById(postId);

        // 校验文章归属
        if (posts == null || !posts.getUserId().equals(Math.toIntExact(BaseContext.getCurrentId()))) {
            return Result.error("无权删除该文章");
        }

        // 更新分类计数
        if(posts.getCategoryId() != null) {
            categoriesService.subCount(Long.valueOf(posts.getCategoryId()));
        }
        postsService.removeById(postId);
        return Result.success();
    }

    @GetMapping
    @ApiOperation("获取个人文章列表")
    public Result<PageResult> getUserPosts(UserPostsPageQueryDTO userPostsPageQueryDTO) {
        // 获取当前用户ID并注入
        Long currentUserId = BaseContext.getCurrentId();
        if (currentUserId == null) {
            // 根据业务需求处理异常情况，例如抛出自定义异常或返回错误响应
            return Result.error("用户未登录");
        }
        userPostsPageQueryDTO.setUserId(Math.toIntExact(currentUserId));

        PageResult pageResult = postsService.pageQuery(userPostsPageQueryDTO);
        return Result.success(pageResult);
    }

    @GetMapping("/{postId}")
    @ApiOperation("根据ID查询文章详情（含浏览量更新）")
    public Result<Posts> getPostById(@PathVariable Integer postId) {
        Posts post = postsService.getPostDetail(postId);
        return Result.success(post);
    }
}
